package com.nervenets.web.controller.handler.user.user;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.nervenets.utils.NumberUtil;
import com.nervenets.utils.SmsAliyun;
import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.Global;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.redis.utils.ISyncExecutor;

import javax.servlet.http.HttpServletRequest;

public class MobileValidationCodeHandler extends Handler<MobileValidationCodeParams> {
    @Override
    public String handle(MobileValidationCodeParams params, HttpServletRequest request) throws Exception {
        if (params.isFindPassword()) {
            final User userByMobile = userDao.getUserByMobile(params.getMobile());
            if (null == userByMobile) return errorMessage(MessageCode.code_444, "手机号未注册，请重新输入");
        }
        final String validationCodeKey = String.format(Global.Constants.MOBILE_VALIDATION_CODE, params.getMobile());
        return (String) redisSyncLocker.keyLock(validationCodeKey, new ISyncExecutor() {
            @Override
            public Object execute(Object o) throws Exception {
                String validationCode = globalService.getGlobalPair(validationCodeKey);
                if (!StringUtils.isEmpty(validationCode))
                    return errorMessage(MessageCode.code_444, globalService.getGlobalPairExpired(validationCodeKey), "验证码已发送！");
                validationCode = String.valueOf(NumberUtil.randomNumber(100000, 999999));
                final SendSmsResponse smsResponse = SmsAliyun.sendSms(params.getMobile(), validationCode);
                if ("OK".equals(smsResponse.getCode())) {
                    globalService.setGlobalPair(validationCodeKey, validationCode, 90);
                    return successMessage();
                }
                return errorMessage(MessageCode.code_444, smsResponse.getMessage());
            }
        }, null);
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
